<template>
  <div class="login" >
    <!-- 头部 -->
    <van-nav-bar
      class="page-nav-bar"
      title="登录"
    >
    <template #left>
      <van-icon name="cross" color="#fff" @click="$router.back()"/>
    </template>
    </van-nav-bar>
    <!-- 登录表单 -->
    <van-form @submit="onSubmit" ref="form">
      <van-field
        v-model="form.mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' },
          {pattern:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号码格式不正确'}
        ]"
      >
        <template #left-icon>
          <i class="iconfont toutiao-shouji"></i>
        </template>
      </van-field>
      <van-field
        v-model="form.code"
        name="code"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写验证码' },
          {pattern:/^[\d]{6}$/, message: '验证码格式不正确'}
        ]"
      >
        <template #left-icon>
          <i class="iconfont toutiao-yanzhengma"></i>
        </template>
        <!-- 发送按钮 -->
        <template #button >
          <van-count-down @finish="isStartStop = false" v-if="isStartStop" :time="6*1000" format="ss s"/>
          <van-button v-else @click="onSend" native-type="button" class="send-btn" size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button class="login-btn" round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getCode, login } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  data () {
    return {
      form: {
        mobile: '',
        code: ''
      },
      isStartStop: false
    }
  },

  created () {

  },

  methods: {
    async onSubmit () {
      try {
        const res = await login(this.form)
        this.$store.commit('initUer', res)
        this.$router.push('/profile')
      } catch (err) {
        console.log(err)
      }
    },
    async onSend () {
      try {
        await this.$refs.form.validate('mobile')
        await getCode(this.form.mobile)
        Toast.success('登录成功')
        this.isStartStop = true
      } catch (err) {
        if (!err.response) {
          return
        }
        if (err.response.status === 429) {
          return Toast.fail('错了,请求次数过多')
        }
        Toast.fail(err, '网络连接出错')
      }
    }
  }
}
</script>

<style scoped lang='less'>
  .login {
    .login-btn {
      width: 694px;
      height: 88px;
      background: #6DB4FB;
      border: none;
      border-radius: 10px;
    }
    .iconfont {
      font-size: 37px;
    }
    .send-btn {
      width: 152px;
      height: 46px;
      background: #EDEDED;
      border: none;
      border-radius: 23px;
      padding: 0;
      font-size: 22px;
      color: #666666;
    }
  }
</style>
